#include "display_buffer.h"
#include "mpp_display_util.h"
#include <drm_fourcc.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/mman.h>
#include <string.h>


#define CODEC_ALIGN(x, a)   (((x)+(a)-1)&~((a)-1))
display_buffer::display_buffer():display_dev("/dev/dri/card0")
{
    mpp_display_init_element();
}
display_buffer::~display_buffer()
{

}




int display_buffer::add_fb_sp_bo(display_dev::sp_bo *bo, uint32_t format)
{
    int ret;
    uint32_t handles[4], pitches[4], offsets[4];

    handles[0] = bo->handle;
    pitches[0] = bo->pitch;
    offsets[0] = 0;

    if(format == DRM_FORMAT_NV12 || format == DRM_FORMAT_NV16) {
        handles[1] = bo->handle;
        pitches[0] = bo->width;
        pitches[1] = bo->width;
        offsets[1] = bo->width * bo->height;
    }

    ret = drmModeAddFB2(mpp_display_dev_get_fd(), bo->width, bo->height,
                        format, handles, pitches, offsets,
                        &bo->fb_id, bo->flags);
    if (ret) {
        printf("failed to create fb ret=%d\n", ret);
        return ret;
    }
    return 0;
}

int display_buffer::map_sp_bo(display_dev::  sp_bo* bo)
{
    int ret;
    struct drm_mode_map_dumb md;

    if (bo->map_addr)
        return 0;

    md.handle = bo->handle;
    ret = drmIoctl(mpp_display_dev_get_fd(), DRM_IOCTL_MODE_MAP_DUMB, &md);
    if (ret) {
        printf("failed to map sp_bo ret=%d\n", ret);
        return ret;
    }

    bo->map_addr = mmap(NULL, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
                        mpp_display_dev_get_fd(), md.offset);
    if (bo->map_addr == MAP_FAILED) {
        printf("failed to map bo ret=%d\n", -errno);
        return -errno;
    }
    return 0;
}
display_dev:: sp_bo*  display_buffer::create_sp_bo(uint32_t width, uint32_t height,
                                uint32_t depth, uint32_t bpp, uint32_t format, int fd,uint32_t flags)
{
    int ret = 0;
    mpp_disp_util::depict_shape shape;
    display_dev::sp_bo* bo = NULL;
    if(fd < 0)
        return NULL;
    bo = new display_dev::sp_bo();
    if (!bo)
            return NULL;

    ret =drmPrimeFDToHandle(mpp_display_dev_get_fd(), fd, &bo->handle);
    if(ret){
        printf("failed   drmPrimeFDToHandle ret=%d\n", ret);
        return NULL;
    }
    bo->fd = mpp_display_dev_get_fd();

    width = CODEC_ALIGN(width, 16);
    height = CODEC_ALIGN(height, 16);

    
    bo->width = width;
    bo->height = height;

    
    bo->depth = depth;
    bo->bpp = bpp;
    bo->format = format;
    bo->flags = 0;

    mpp_disp_util::mpp_format_depict_sharp(format,
									width, height,bo->handle, mpp_disp_util::mpp_format_get_pitch(format,width),&shape);

    printf("width %d height %d,    ==== pitches[0] %d pitches[1] %d offsets[0] %d offsets[1] %d \n",
                                                                                 bo->width,bo->height, 
                                                                                shape.pitches[0],shape.pitches[1], 
                                                                                                shape.offsets[0], shape.offsets[1]);
    ret = drmModeAddFB2(mpp_display_dev_get_fd(), 
                                            bo->width, bo->height,
                                            bo->format, shape.handles, shape.pitches, shape.offsets,
                                            &bo->fb_id, bo->flags);
    if (ret != 0) {
        printf("failed to exec drmModeAddFb2.\n");
        return NULL;
    }
    // ret = map_sp_bo(bo);
    // if (ret) {
    //     printf("failed to map bo ret=%d\n", ret);
    //     goto err;
    // }
    return bo;


    err:
    free_sp_bo(bo,false);
    return NULL;

}
display_dev::sp_bo* display_buffer::create_sp_bo(uint32_t width, uint32_t height,
                                                                                uint32_t depth, uint32_t bpp, uint32_t format, uint32_t flags)
{
    int ret;
    struct drm_mode_create_dumb cd;
    display_dev::sp_bo* bo = NULL;

    memset(&cd, 0, sizeof(cd));

    // bo = (struct sp_bo *) calloc(1, sizeof(*bo));
    // if (!bo)
    //     return NULL;
    bo = new display_dev::sp_bo();
    if (!bo)
         return NULL;

    cd.height = height;
    cd.width = width;
    cd.bpp = bpp;
    cd.flags = flags;

    ret = drmIoctl(mpp_display_dev_get_fd(), DRM_IOCTL_MODE_CREATE_DUMB, &cd);
    if (ret) {
        printf("failed to create sp_bo %d\n", ret);
        goto err;
    }

    bo->fd = mpp_display_dev_get_fd();
    bo->width = width;
    bo->height = height;
    bo->depth = depth;
    bo->bpp = bpp;
    bo->format = format;
    bo->flags = flags;

    bo->handle = cd.handle;
    bo->pitch = cd.pitch;
    bo->size = cd.size;

    ret = add_fb_sp_bo(bo, format);
    if (ret) {
        printf("failed to add fb ret=%d\n", ret);
        goto err;
    }

    ret = map_sp_bo(bo);
    if (ret) {
        printf("failed to map bo ret=%d\n", ret);
        goto err;
    }

    return bo;

    err:
    free_sp_bo(bo,true);
    return NULL;
}
void display_buffer::fill_bo(display_dev:: sp_bo *bo, uint8_t a, uint8_t r, uint8_t g, uint8_t b)
{
    draw_rect(bo, 0, 0, bo->width, bo->height, a, r, g, b);
}
void display_buffer::draw_rect(display_dev:: sp_bo *bo, uint32_t x, uint32_t y, uint32_t width,
            uint32_t height, uint8_t a, uint8_t r, uint8_t g, uint8_t b)
{
    uint32_t i, j, xmax = x + width, ymax = y + height;

    if (xmax > bo->width)
        xmax = bo->width;
    if (ymax > bo->height)
        ymax = bo->height;

    for (i = y; i < ymax; i++) {
        uint8_t* row = (uint8_t*)bo->map_addr + i * bo->pitch;

        for (j = x; j < xmax; j++) {
            uint8_t* pixel = row + j * 4;

            if (bo->format == DRM_FORMAT_ARGB8888 || bo->format == DRM_FORMAT_XRGB8888) {
                pixel[0] = b;
                pixel[1] = g;
                pixel[2] = r;
                pixel[3] = a;
            } else if (bo->format == DRM_FORMAT_RGBA8888) {
                pixel[0] = r;
                pixel[1] = g;
                pixel[2] = b;
                pixel[3] = a;
            }
        }
    }
}
void display_buffer::free_sp_bo(display_dev::sp_bo *bo,bool isDestroyDumb)
{
    int ret;
    struct drm_mode_destroy_dumb dd;

    if (!bo)
        return;

    if (bo->map_addr)
        munmap(bo->map_addr, bo->size);

    if (bo->fb_id) {
        ret = drmModeRmFB(mpp_display_dev_get_fd(), bo->fb_id);
        if (ret)
            printf("Failed to rmfb ret=%d!\n", ret);
    }

    if (bo->handle) {
        

        struct drm_gem_close req = {
                    .handle = bo->handle,
        };
        drmIoctl(mpp_display_dev_get_fd(), DRM_IOCTL_GEM_CLOSE, &req);


        if(isDestroyDumb){
            dd.handle = bo->handle;
            ret = drmIoctl(mpp_display_dev_get_fd(), DRM_IOCTL_MODE_DESTROY_DUMB, &dd);
            if (ret)
                printf("Failed to destroy buffer ret=%d\n", ret);
        }
        
    }

    delete bo;
}